package com.zf.yichat.config.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.ArrayList;

@Slf4j
@Component
public class MyHandler implements WebSocketHandler {


    // 保存所有的用户session
    private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("connect websocket success.......");

        users.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String content = message.getPayload().toString();
        TextMessage textMessage = new TextMessage(content, true);
        // 调用方法（发送消息给所有人）
        sendMsgToAllUsers(textMessage);

        // 处理同一个手机地址和IP地址登录多个账号
//        SysSensitives sensitives = sysSensitivesService.selectSensitivesById(1);
//        try {
//            Client client = Client.getInstance();
//            log.info("client:" + client.hashCode());
//
//            while(true) {
//                Thread.sleep(1000);
//                if(client.isOpen()) {
//                    client.send(JSON.toJSONString(sensitives));
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            log.error("推送通知失败：", e);
//        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.warn("handleTransportError");
        users.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("connect websocket closed.......");
        users.remove(session);
    }

    // 给所有用户发送 信息
    public void sendMsgToAllUsers(WebSocketMessage<?> message) throws Exception {
        for (WebSocketSession user : users) {
            user.sendMessage(message);
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
